package com.dao.impl;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Repository;

import com.dao.IRetPrdIndtDao;
import com.model.Ret_prd_in;
import com.model.Ret_prd_indt;
import com.model.Ret_prd_indtId;
import com.util.Util;

@Repository
public class RetPrdIndtHibernateDao extends
		GenericHibernateDao<Ret_prd_indt, Ret_prd_indtId> implements
		IRetPrdIndtDao {

	public List<Ret_prd_indt> getPrdIndtByBox(String boxId) {
		List<Ret_prd_indt> ret_prd_indtList = new ArrayList<Ret_prd_indt>();
		String querySql = "FROM Ret_prd_indt where mtrl_box_id_fk ='" + boxId
				+ "'";
		ret_prd_indtList = this.find(querySql);
		return ret_prd_indtList;
	}

	public Boolean hasUserInputSlotInMtrlBox(Ret_prd_in ret_prd_in,
			String inputSlotNo) {
		List<Ret_prd_indt> ret_prd_indtList = new ArrayList<Ret_prd_indt>();
		String querySql = "FROM Ret_prd_indt where mtrl_box_id_fk ='"
				+ ret_prd_in.getId().getMtrl_box_id()
				+ "' and mtrl_slot_no = '" + inputSlotNo + "'";
		ret_prd_indtList = this.find(querySql);
		if (ret_prd_indtList.isEmpty()) {
			return false;
		}
		return true;
	}
	
	
	/**
	 * 创建产品ID，并自动补齐断掉的流水号
	 * @param prdKey
	 * @return
	 */
	public String createPrdIdLoop(String prdKey) {
		Integer spcLength = prdKey.length() + 4;
		DecimalFormat df_X = new DecimalFormat("0000");
		Integer serealNo_A = 0;
		Integer serealNo_B = 0;
		String serealNo = "0001";
		String prdId = Util.getRvTime();
		String sqlStr = "SELECT VDR_PRD_SEQ_ID FROM RET_PRD_INDT WHERE VDR_PRD_SEQ_ID LIKE'"
				+ prdKey +"%' and length(VDR_PRD_SEQ_ID) = '" + spcLength + "' ORDER BY VDR_PRD_SEQ_ID ASC";
		
		List<Object> prdIdList = this.findBySQL(sqlStr);
		if (prdIdList.isEmpty()) {
			prdId = prdKey + serealNo;
		}else{
			for(int i=0; i<prdIdList.size(); i++){
				serealNo_A = Integer.valueOf(prdIdList.get(i).toString().substring(prdKey.length()));//获取前一个prd_id的sereal no
				/**
				 * 获取后一个prd_id的sereal no
				 * 如果前一个prd_id是最后一个，则serealNo = serealNo_A + 1
				 * 否则比较serealNo_A & serealNo_B
				 */
				if(i == 0 && serealNo_A != 1){
					prdId = prdKey + serealNo;
					break;
				}
				if((i+1) < prdIdList.size()){
					serealNo_B = Integer.valueOf(prdIdList.get(i+1).toString().substring(prdKey.length()));
					if((serealNo_B - serealNo_A) > 1){
						serealNo = df_X.format(serealNo_A + 1);
						prdId = prdKey + serealNo;
						break;
					}
				}else{
					serealNo = df_X.format(serealNo_A + 1);
					prdId = prdKey + serealNo;
				}
			}
		}
		return prdId;
	}
}
